function asciiwrite(filename, filecont, append, linedelim)
% asciiwrite  - writes a textfile from a char array to file
%
% FORMAT:       asciiwrite(filename, filecont [, append, linedelim])
%
% Input Fields:
%       filename    name to a file, preferably absolute path
%       filecont    char array to write
%       append      if true, content will be appended to file
%       linedelim   optional char array with line delimiter
%
% Note: if no linedelim is given, lines are limited system dependend
%
% See also asciiread, binwrite.

% Version:  v0.7f
% Build:    8110521
% Date:     Nov-05 2008, 9:00 PM CET
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% enough arguments ?
if nargin < 2 || ...
   ~ischar(filename) || ...
    isempty(filename) || ...
   ~ischar(filecont)
    error( ...
        'BVQXtools:BadArgument', ...
        'Bad or too few arguments. Try ''help %s''.', ...
        mfilename ...
    );
end

% options
if nargin < 3 || ...
    isempty(append) || ...
   ~append(1)
    omode = 'w';
else
    omode = 'a';
end
if nargin < 4 || ...
   ~ischar(linedelim)
    if ispc
        linedelim = char([13, 10]);
    else
        linedelim = char(10);
    end
end

% standard check on filename
if ispc
    filename = strrep(filename, '/', filesep);
else
    filename = strrep(filename, '\', filesep);
end

% get file pointer
ofp = fopen(filename, omode);
if ofp < 1
    error( ...
        'BVQXtools:FileNotWritable', ...
        'Couldn''t write to file ''%s''.', ...
        filename ...
    );
end
frewind(ofp);

% some more sanity checks on content
if iscell(filecont)
    filecont = char(filecont);
end

% make a 2-D char array a cell -> glue with linedelim
if all(size(filecont) > 1)
    filecont = gluetostringc(cellstr(filecont), linedelim);
end

% write output
fwrite(ofp, filecont, 'uchar');
fclose(ofp);
